package com.talking.service;

import com.talking.pojo.Message;
import com.talking.tool.SocketConfig;

import javax.swing.*;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class SocketService {
    private static Socket clientSocket;
    private static ObjectOutputStream clientOutput;
    private static ObjectInputStream clientInput;

    public SocketService(){
        try {
            //创建客户端socket
            SocketConfig config = new SocketConfig();
            System.out.println(config.toString());
            clientSocket = new Socket(config.getServerSocketIP(),config.getServerPort());
            System.out.println("建立客户端");
            clientOutput = new ObjectOutputStream(clientSocket.getOutputStream());
            clientInput = new ObjectInputStream(clientSocket.getInputStream());

            System.out.println("服务器连接成功!");

        } catch (IOException e) {
            System.out.println("服务器连接失败！");
            e.printStackTrace();
            close();
            JOptionPane.showMessageDialog(null,"服务器连接失败！","消息提示",JOptionPane.WARNING_MESSAGE);	//消息对话框
        }
    }

    public static void writeMessage(Message message){
        try {
            clientOutput.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("数据发送失败！");
            JOptionPane.showMessageDialog(null,"数据发送失败！","消息提示",JOptionPane.WARNING_MESSAGE);	//消息对话框
        }
    }

    public static ObjectInputStream getClientInput() {
        return clientInput;
    }

    public static ObjectOutputStream getClientOutput() {
        return clientOutput;
    }
    public Socket getSocket(){
        return clientSocket;
    }

    public static void close() {
        Closeable[] closeables = new Closeable[]{clientSocket,clientOutput,clientInput};

        for (Closeable closeable : closeables) {
            if (closeable!=null) {
                try {
                    closeable.close();
                    closeable = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
